<?php

/**
 * supply functions to validate code & jump login
 *
 * @package SGN_Core
 * @version $Id: Launcher.php 1413 2012-02-29 07:10:26Z locth $
 * @author $Author: locth $
 *
 */
class SGN_Launcher
{
    static public function checkReadyToJump($params)
    {
        // check input
        $result = 0;
        if(!is_array($params)){
            return $result;
        }

        // validating sign
        if($params['p']){
            $productConfig = SGN_Application::getConfig('sgn', 'api', 'jump')->get($params['p']);
            if($productConfig){
                $productConfig = $productConfig->toArray();
            }

            // check time
            if ($params['time'] + $productConfig['timeout'] < SGN_Application::getCurrentTime()) {
                return -1; // expired
            }

            $authCode = md5($productConfig['key'] . $params['accountname'] . $productConfig['code'] . $params['time']);
        }

        SGN_Account::logout();
        if ($params['sign'] && $authCode == strtolower($params['sign'])) {
            // save product code in session
            $session = SGN_Application::get('session');
            $session->set('product', $params['p']);

            // auto jump login
            //SGN_SSO::jump($params['accountname'], $params['successUrl']);
            $result = 1;
        }

        return $result;
    }

    static public function validate($params, &$accountName)
    {
        $session = SGN_Application::get('session');

        // get account name from params
        if($params){
            $accountName = SGN_SSO::parseSsoParam($params);
        }
        $product = $session->get('product');

        // init account object
        if(!$accountName){
            $accountName = $session->get('username');
        }else{
            // save to session
            $session->set('username', $accountName);
            $session->set('loggedin', 1);

            // save to cookie
            SGN_Application::setCookie(APPLICATION_ENV.'_username', $accountName);
            SGN_Application::setCookie(APPLICATION_ENV.'_loggedin', 1);
        }

        // check valid
        $productConfig = SGN_Application::getConfig('sgn', 'api', 'jump')->toArray();
        if(    !$accountName
            || !$product
            || $accountName != $session->get('username')
            || !array_key_exists($product, $productConfig)){
            return false;
        }
        return true;
    }
}
